package com.cake.bigdata.starter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cake.bigdata.starter.exception.error.CommonErrorCode;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * 返回统一数据结构
 *
 * @author gst
 * @date 2019-12-20 20:30
 */
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {

    /**
     * 成功，返回数据
     */
    public static final Integer SUCCESS = 0;
    /**
     * 错误，返回错误信息
     */
    public static final Integer ERROR   = 1;

    /**
     * 是否成功 0成功 1失败
     */
    private             Integer state;

    /**
     * 服务器当前时间戳
     */
    private Long ts = System.currentTimeMillis();

    /**
     * 成功数据
     */
    private T data;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误描述
     */
    private String message;

    public static <T> Result<T> ofSuccess() {
        Result<T> result = new Result<>();
        result.state = SUCCESS;
        return result;
    }

    public static <T> Result<T> ofSuccess(T data) {
        Result<T> result = new Result<>();
        result.state = SUCCESS;
        result.setData(data);
        return result;
    }

    public static <T> Result<T> ofFail(String code, String message) {
        Result<T> result = new Result<>();
        result.state = ERROR;
        result.code = code;
        result.message = message;
        return result;
    }

    public static <T> Result<T> ofFail(CommonErrorCode resultEnum) {
        Result<T> result = new Result<>();
        result.state = ERROR;
        result.code = resultEnum.getCode();
        result.message = resultEnum.getMessage();
        return result;
    }

    /**
     * 获取 json
     */
    @SuppressWarnings("unused")
    public String buildResultJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", this.state);
        jsonObject.put("code", this.code);
        jsonObject.put("ts", this.ts);
        jsonObject.put("message", this.message);
        jsonObject.put("data", this.data);
        return JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect);
    }
}
